#include <stdlib.h>
#include <stdio.h>
#include <cbm.h>
#include <string.h>

#include "Buffers.h"
#include "Drives.h"
#include "Trim.h"

#pragma code-name("DPCODE");
#pragma rodata-name("DPCODE");

void initializeDrives()
{
	unsigned char i = 7, c = 0, r = 0;
	char msg[40];

	for(i = 0; i < 6; ++i)
	{
		drives[i].device = 0;
		drives[i].drive = 0;
		memset(drives[i].path, 0, sizeof(drives[i].path));
		drives[i].type = CBM15x1;
	}

	for(i = 7; i < 24; ++i)
	{
		if((r = cbm_open(15, i, 15, "ui")) == 0)
		{
			memset(msg, 0, sizeof(msg));
			if(cbm_read(15, msg, sizeof(msg)) > 0)
			{
				printf("\n%02u: ", i);
				if(strstr(msg,"1541") != NULL ||
					strstr(msg,"1571") != NULL ||
					strstr(msg,"1581") != NULL)
				{
					printf("15x1");
					drives[c].type = CBM15x1;
				}
				else if(strstr(msg,"sd2iec") != NULL ||
					strstr(msg,"uiec") != NULL)
				{
					printf("SD2IEC");
					drives[c].type = uIEC;
				}
				else if(strstr(msg,"cmd") != NULL)
				{
					printf("CMD");
					drives[c].type = CMD;
				}
				else if(strstr(msg,"comet") != NULL)
				{
					printf("Comet");
					drives[c].type = Comet;
				}
				//else if(strstr(msg,"ide64") != NULL)
				//{
				//	printf("IDE64 Drive");
				//	drives[c].type = IDE64;
				//}
				else if(strstr(msg,"vice") != NULL)
				{
					printf("VICE");
					drives[c].type = VICE;
				}
				else
				{
					printf("Other 15x1");
					drives[c].type = CBM15x1;
				}
				drives[c].device = i;
				drives[c].drive = 0;
				memset(drives[c].path, 0, sizeof(drives[c].path));
				if(drives[c].type != CBM15x1)
				{
					if(drives[c].type == VICE)
					{
						cbm_write(15, "cd:/", 4);
					}
					else 
					{
						cbm_write(15, "cd//", 4);
					}
					cbm_read(15, buffer1, sizeof(buffer1));
					if(buffer1[0] == '0' && buffer1[1] == '0')
					{
						drives[c].path[0] = '/';
						if(drives[c].type != VICE)
						{
							drives[c].path[1] = '/';
						}
					}
					else
					{
						printf("\n%s", buffer1);
					}
				}
				++c;
				if(c == 6) break;
			}
			cbm_close(15);
		}
		else
		{
			cbm_close(15);
			//printf("\n%02u: no drive. (%u)", i, r);
		}
	}

	cbm_close(15);
}

unsigned char getDrive(unsigned char device)
{
	unsigned char i = 0;

	for(; i < 6; ++i)
	{
		if(drives[i].device == device)
		{
			return i;
		}
	}

	return 0xFF;
}

